<template>
  <div class="doctor-container">
    <div class="header">
      <h2>中医体质辨识系统</h2>
      <div class="header-actions">
        <button class="chat-btn" @click="goToChat">聊天室</button>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </div>
    
    <div class="content">
      <div class="welcome-section">
        <h1>医生工作站</h1>
        <p>欢迎回来，{{ doctorName }}医生</p>
      </div>
      
      <!-- 替换原有的dashboard部分，改为选项卡 -->
      <div class="bshf-panel">
        <div class="tabs">
          <div 
            v-for="tab in tabs" 
            :key="tab.value" 
            :class="['tab', { active: activeTab === tab.value }]"
            @click="activeTab = tab.value"
          >
            {{ tab.label }}
            <span class="count">({{ getTabCount(tab.value) }})</span>
          </div>
        </div>
        <!-- 添加图表弹窗 -->
        <el-dialog
          v-model="chartDialogVisible"
          title="体质分析图表"
          width="80%"
          :before-close="handleChartDialogClose"
          destroy-on-close
        >
          <div class="chart-container">
            <div ref="radarChartRef" class="radar-chart"></div>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <button class="complete-btn" @click="completeIdentification">完成辨识</button>
            </div>
          </template>
        </el-dialog>
        
        <!-- 添加回访弹窗 -->
        <el-dialog
          v-model="followupDialogVisible"
          title="开始回访"
          width="40%"
          :before-close="handleFollowupDialogClose"
          destroy-on-close
        >
          <div class="followup-form">
            <div class="form-item">
              <label>选择问卷：</label>
              <el-select v-model="followupForm.quesnaireId" placeholder="请选择问卷">
                <el-option
                  v-for="item in questionnaireList"
                  :key="item.id"
                  :label="item.queslistName"
                  :value="item.id"
                />
              </el-select>
            </div>
            <div class="form-item">
              <label>备注：</label>
              <el-input
                v-model="followupForm.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入回访备注"
              />
            </div>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <button class="cancel-btn" @click="followupDialogVisible = false">取消</button>
              <button class="confirm-btn" @click="startFollowup">确定</button>
            </div>
          </template>
        </el-dialog>
        <!-- 在图表弹窗和回访弹窗后添加趋势弹窗 -->
        <el-dialog
          v-model="trendDialogVisible"
          title="患者体质趋势分析"
          width="80%"
          :before-close="handleTrendDialogClose"
          destroy-on-close
        >
          <div v-if="loadingTrend" class="loading-container">
            <p>加载中...</p>
          </div>
          <div v-else class="trend-container">
            <div v-if="constitutionTrend.length === 0" class="empty-data">
              <p>暂无足够的数据生成趋势图</p>
            </div>
            <div v-else>
              <div ref="trendChartRef" class="trend-chart"></div>
              
              <div class="answer-changes">
                <h3>答案变化分析</h3>
                <div v-if="answerChanges.length === 0" class="no-changes">
                  <p>最近两次测试没有答案变化</p>
                </div>
                <div v-else class="changes-list">
                  <div v-for="(change, index) in answerChanges" :key="index" class="change-item">
                    <p class="question">{{ change.question }}</p>
                    <div class="answers">
                      <p class="previous">上次答案: <span>{{ change.previousAnswer }}</span></p>
                      <p class="latest">本次答案: <span>{{ change.latestAnswer }}</span></p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-dialog>
        
        <div class="bshf-list">
          <div v-if="loading" class="loading">
            <p>加载中...</p>
          </div>
          
          <div v-else-if="filteredBshfList.length === 0" class="empty-list">
            <p>暂无{{ getActiveTabLabel() }}记录</p>
          </div>
          
          <div v-else class="bshf-items">
            <div v-for="item in filteredBshfList" :key="item.id" class="bshf-item">
              <div class="bshf-info">
                <p><strong>患者:</strong> {{ userMap[item.userinfoId] || `ID: ${item.userinfoId}` }}</p>
                <p><strong>问卷:</strong> {{ questionnaireMap[item.quesnaireId] || `ID: ${item.quesnaireId}` }}</p>
                <p><strong>体质类型:</strong> {{ resultMap[item.resultId] || '未知' }}</p>
                <p><strong>状态:</strong> {{ item.status }}</p>
                <p><strong>创建时间:</strong> {{ formatDate(item.createTime) }}</p>
              </div>
              <div class="bshf-actions">
                <button 
                  class="action-btn" 
                  @click="handleAction(item)"
                  v-if="getActionText(item.status)"
                >
                  {{ getActionText(item.status) }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick,onUnmounted  } from 'vue';
import { useRouter } from 'vue-router';
// 在import部分添加getQuestionList
import { getBSHFList, updateBSHF, insertBSHF } from '../api/bshf';
import { getUserList } from '../api/user';
import { getAllQuestionnaires } from '../api/questionnaire';
import { getAnswerResultList } from '../api/answerresult';
import { getTestScoreList } from '../api/testscore';
import { getQuestionList } from '../api/question'; // 添加这一行
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';

const router = useRouter();
const doctorName = ref('医生');
const doctorId = ref(null);
const bshfList = ref([]);
const loading = ref(false);

// 添加用户和问卷映射
const userMap = ref({});
const questionnaireMap = ref({});
const resultMap = ref({});

// 定义选项卡
const tabs = [
  { label: '未辨识', value: '未辨识' },
  { label: '已辨识', value: '已辨识' },
  { label: '回访中', value: '回访中' },
  { label: '已回访', value: '已回访' }
];

const activeTab = ref('未辨识');

// 根据选项卡筛选数据
const filteredBshfList = computed(() => {
  return bshfList.value.filter(item => item.status === activeTab.value);
});

// 获取每个选项卡的数量
const getTabCount = (status) => {
  return bshfList.value.filter(item => item.status === status).length;
};

// 获取当前选项卡的标签
const getActiveTabLabel = () => {
  const tab = tabs.find(t => t.value === activeTab.value);
  return tab ? tab.label : '';
};

// 根据状态获取操作按钮文本
const getActionText = (status) => {
  switch (status) {
    case '未辨识': return '查看图表';
    case '已辨识': return '开始回访';
    case '回访中': return '';
    case '已回访': return '查看趋势';
    default: return '操作';
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 在图表相关变量下方添加趋势弹窗相关变量
const trendDialogVisible = ref(false);
const trendChartRef = ref(null);
let trendChartInstance = null;
const currentPatientId = ref(null);
const patientAnswers = ref([]);
const answerChanges = ref([]);
const constitutionTrend = ref([]);
const loadingTrend = ref(false);

// 添加图表相关变量
const chartDialogVisible = ref(false);
const radarChartRef = ref(null);
let radarChartInstance = null;
const currentResultId = ref(null);
// 添加当前处理的BSHF记录ID
const currentBshfId = ref(null);

// 体质名称映射
const constitutionNames = {
  1: '平和质',
  2: '气虚质',
  3: '阳虚质',
  4: '阴虚质',
  5: '痰湿质',
  6: '湿热质',
  7: '血瘀质',
  8: '气郁质',
  9: '特禀质'
};

// 解析体质类型
const parseConstitutionType = (answerlistResult) => {
  try {
    if (!answerlistResult) return '未知体质';
    
    const answerData = JSON.parse(answerlistResult);
    
    // 如果解析后的数据包含constitutionType字段，直接返回
    if (answerData && answerData.constitutionType) {
      return answerData.constitutionType;
    }
    
    // 兼容旧数据格式
    if (typeof answerData === 'string') return answerData;
    
    // 如果是对象，找出最高分的体质
    if (typeof answerData === 'object' && !Array.isArray(answerData)) {
      let maxScore = -1;
      let maxType = null;
      
      for (const key in answerData) {
        const score = parseFloat(answerData[key]);
        if (score > maxScore) {
          maxScore = score;
          maxType = key;
        }
      }
      
      return maxType || "未知体质";
    }
    
    return "未知体质";
  } catch (e) {
    console.error('解析体质类型失败:', e);
    return "未知体质";
  }
};

// 添加回访弹窗相关变量
const followupDialogVisible = ref(false);
const followupForm = ref({
  quesnaireId: '',
  remark: '',
  userinfoId: null,
  doctorId: null,
  bshfId: null
});
const questionnaireList = ref([]);

// 显示回访弹窗
const showFollowupDialog = async (item) => {
  // 重置表单
  followupForm.value = {
    quesnaireId: '',
    remark: '',
    userinfoId: item.userinfoId,
    doctorId: doctorId.value,
    bshfId: item.id
  };
  
  // 加载问卷列表
  try {
    const res = await getAllQuestionnaires();
    if (res?.code === 0 && Array.isArray(res.data)) {
      questionnaireList.value = res.data;
    } else {
      questionnaireList.value = [];
    }
  } catch (error) {
    console.error('加载问卷列表失败:', error);
    questionnaireList.value = [];
  }
  
  // 显示弹窗
  followupDialogVisible.value = true;
};

// 关闭回访弹窗
const handleFollowupDialogClose = () => {
  followupDialogVisible.value = false;
};

// 开始回访
const startFollowup = async () => {
  // 表单验证
  if (!followupForm.value.quesnaireId) {
    return ElMessage.warning('请选择问卷');
  }
  
  try {
    // 先检查是否已经存在该患者的回访中记录
    const checkParams = {
      userinfoId: followupForm.value.userinfoId,
      doctorId: followupForm.value.doctorId,
      status: '回访中',
      del: 0
    };
    
    const checkRes = await getBSHFList(checkParams);
    
    if (checkRes.code === 0 && checkRes.data && checkRes.data.length > 0) {
      return ElMessage.warning('您当前已经对该患者进行回访');
    }
    
    // 构造新记录数据
    const newRecord = {
      doctorId: followupForm.value.doctorId,
      userinfoId: followupForm.value.userinfoId,
      resultId: followupForm.value.resultId,  // 使用原记录的resultId
      quesnaireId: followupForm.value.quesnaireId,
      remark: followupForm.value.remark,
      status: '回访中',
      // 以下是可能需要的基础字段
      createBy: doctorId.value,
      updateBy: doctorId.value
    };

    // 调用插入接口
    const res = await insertBSHF(newRecord);
    
    if (res.code === 0) {
      ElMessage.success('回访已开始');
      // 关闭弹窗
      followupDialogVisible.value = false;
      // 重新加载数据
      loadBshfData();
    } else {
      throw new Error(res.msg || '操作失败');
    }
  } catch (error) {
    console.error('开始回访失败:', error);
    ElMessage.error(error.message || '操作失败，请稍后再试');
  }
};

// 显示图表弹窗 (删除重复的函数定义，只保留一个)
const showChartDialog = async (resultId, bshfId) => {
  currentResultId.value = resultId;
  currentBshfId.value = bshfId;
  chartDialogVisible.value = true;
  
  // 等待DOM更新后初始化图表
  await nextTick();
  initRadarChart();
};

// 添加完成辨识方法
const completeIdentification = async () => {
  if (!currentBshfId.value) {
    ElMessage.warning('无法获取辨识记录信息');
    return;
  }
  
  try {
    // 查找当前记录
    const currentRecord = bshfList.value.find(item => item.id === currentBshfId.value);
    if (!currentRecord) {
      throw new Error('找不到对应的辨识记录');
    }
    
    // 调用更新接口
    const res = await updateBSHF({
      ...currentRecord,
      status: '已辨识'
    });
    
    if (res.code === 0) {
      ElMessage.success('辨识完成');
      // 关闭弹窗
      handleChartDialogClose();
      // 重新加载数据
      loadBshfData();
    } else {
      throw new Error(res.msg || '更新失败');
    }
  } catch (error) {
    console.error('完成辨识失败:', error);
    ElMessage.error(error.message || '操作失败，请稍后再试');
  }
};

const handleAction = (item) => {
  // 根据不同状态执行不同操作
  switch (item.status) {
    case '未辨识':
      // 显示图表弹窗，传入bshfId
      showChartDialog(item.resultId, item.id);
      break;
    case '已辨识':
      // 显示回访弹窗
      showFollowupDialog(item);
      break;
    case '回访中':
      // 完成回访操作
      completeFollowup(item.id);
      break;
    case '已回访':
      // 显示趋势弹窗
      showTrendDialog(item.userinfoId);
      break;
    default:
      break;
  }
};

// 显示趋势弹窗
const showTrendDialog = async (patientId) => {
  currentPatientId.value = patientId;
  trendDialogVisible.value = true;
  loadingTrend.value = true;
  
  try {
    // 获取患者的所有测试结果
    const resultRes = await getAnswerResultList({ userinfoId: patientId });
    
    if (resultRes.code !== 0 || !resultRes.data || resultRes.data.length === 0) {
      throw new Error('获取患者测试结果失败');
    }
    
    // 按时间排序结果
    const sortedResults = resultRes.data.sort((a, b) => 
      new Date(a.createTime) - new Date(b.createTime)
    );
    
    // 提取体质类型趋势
    constitutionTrend.value = sortedResults.map(result => ({
      id: result.id,
      time: formatDate(result.createTime),
      type: parseConstitutionType(result.answerlistResult)
    }));
    
    // 提取答案变化
    patientAnswers.value = [];
    answerChanges.value = [];
    
    // 解析每次测试的答案
    for (const result of sortedResults) {
      try {
        const answerData = JSON.parse(result.answerlistResult);
        if (answerData && answerData.choice) {
          patientAnswers.value.push({
            resultId: result.id,
            time: formatDate(result.createTime),
            answers: answerData.choice
          });
        }
      } catch (e) {
        console.error('解析答案数据失败:', e);
      }
    }
    
    // 如果有多次测试，比较答案变化
    if (patientAnswers.value.length >= 2) {
      // 获取最近两次测试
      const latest = patientAnswers.value[patientAnswers.value.length - 1];
      const previous = patientAnswers.value[patientAnswers.value.length - 2];
      
      // 比较答案变化
      for (const quesId in latest.answers) {
        if (previous.answers[quesId] && latest.answers[quesId] !== previous.answers[quesId]) {
          // 查找问题内容
          const question = await getQuestionContent(quesId);
          
          answerChanges.value.push({
            questionId: quesId,
            question: question,
            previousAnswer: getOptionText(previous.answers[quesId]),
            latestAnswer: getOptionText(latest.answers[quesId])
          });
        }
      }
    }
    
  } catch (error) {
    console.error('加载趋势数据失败:', error);
    ElMessage.error('加载趋势数据失败');
  } finally {
    loadingTrend.value = false;
    // 确保DOM更新后再初始化图表（此时trendChartRef所在容器已渲染）
    await nextTick(); 
    initTrendChart(); 
  }
};

// 获取问题内容
const getQuestionContent = async (quesId) => {
  try {
    const res = await getQuestionList([quesId]);
    if (res.code === 0 && res.data && res.data.length > 0) {
      return res.data[0].quesContent;
    }
    return `问题ID: ${quesId}`;
  } catch (e) {
    console.error('获取问题内容失败:', e);
    return `问题ID: ${quesId}`;
  }
};

// 获取选项文本
const getOptionText = (optionId) => {
  const optionMap = {
    1: 'A. 没有',
    2: 'B. 很少',
    3: 'C. 有时',
    4: 'D. 经常',
    5: 'E. 总是'
  };
  return optionMap[optionId] || `选项ID: ${optionId}`;
};

// 关闭趋势弹窗
const handleTrendDialogClose = () => {
  if (trendChartInstance) {
    trendChartInstance.dispose();
    trendChartInstance = null;
  }
  trendDialogVisible.value = false;
  currentPatientId.value = null;
};

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) {
    console.error('趋势图表DOM元素不存在');
    return;
  }
  
  if (constitutionTrend.value.length === 0) {
    console.error('没有体质趋势数据可供显示');
    return;
  }
  
  console.log('开始初始化趋势图表');
  
  // 如果已存在图表实例，先销毁
  if (trendChartInstance) {
    trendChartInstance.dispose();
    trendChartInstance = null;
  }
  
  // 创建新的图表实例
  trendChartInstance = echarts.init(trendChartRef.value);
  
  // 提取时间和体质类型
  const times = constitutionTrend.value.map(item => item.time);
  const types = constitutionTrend.value.map(item => item.type);
  
  console.log('图表时间数据:', times);
  console.log('图表体质类型数据:', types);
  
  // 获取所有出现的体质类型
  const uniqueTypes = [...new Set(types)];
  console.log('唯一体质类型:', uniqueTypes);
  
  // 为每种体质类型创建一个数据系列
  const series = uniqueTypes.map(type => {
    // 创建数据点，如果当前时间点的体质类型匹配，则为1，否则为0
    const data = constitutionTrend.value.map(item => 
      item.type === type ? 1 : 0
    );
    
    return {
      name: type,
      type: 'line',
      data: data,
      smooth: true,
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        width: 3
      }
    };
  });
  
  console.log('图表系列数据:', series);
  
  // 设置图表选项
  const option = {
    backgroundColor: '#f9f6f2',
    title: {
      text: '患者体质变化趋势',
      left: 'center',
      textStyle: {
        color: '#8B4513',
        fontFamily: 'KaiTi',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 248, 220, 0.9)',
      borderColor: '#D2B48C',
      textStyle: {
        color: '#8B4513'
      }
    },
    legend: {
      data: uniqueTypes,
      bottom: 0,
      textStyle: {
        color: '#8B4513',
        fontFamily: 'KaiTi'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: times,
      axisLine: {
        lineStyle: {
          color: '#8B4513'
        }
      },
      axisLabel: {
        color: '#8B4513',
        fontFamily: 'KaiTi',
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 1,
      interval: 1,
      axisLine: {
        lineStyle: {
          color: '#8B4513'
        }
      },
      axisLabel: {
        formatter: function(value) {
          return value === 1 ? '是' : '否';
        },
        color: '#8B4513',
        fontFamily: 'KaiTi'
      }
    },
    series: series
  };
  
  console.log('设置图表选项:', option);
  
  try {
    trendChartInstance.setOption(option);
    console.log('趋势图表初始化成功');
    
    // 强制重绘图表
    setTimeout(() => {
      if (trendChartInstance) {
        trendChartInstance.resize();
      }
    }, 200);
  } catch (error) {
    console.error('设置图表选项失败:', error);
  }
};

// 关闭图表弹窗
const handleChartDialogClose = () => {
  if (radarChartInstance) {
    radarChartInstance.dispose();
    radarChartInstance = null;
  }
  chartDialogVisible.value = false;
  currentResultId.value = null;
};

// 初始化雷达图
const initRadarChart = async () => {
  if (!radarChartRef.value || !currentResultId.value) return;
  
  // 如果已存在图表实例，先销毁
  if (radarChartInstance) {
    radarChartInstance.dispose();
  }
  
  // 创建新的图表实例
  radarChartInstance = echarts.init(radarChartRef.value);
  radarChartInstance.showLoading();
  
  try {
    // 获取测试分数数据
    const res = await getTestScoreList({ resultId: currentResultId.value });
    
    if (res.code !== 0 || !res.data) {
      throw new Error('获取测试分数失败');
    }
    
    const scores = res.data;
    
    // 处理分数数据
    const indicators = [];
    const scoreMap = {};
    
    // 将分数转换为映射
    scores.forEach(score => {
      scoreMap[score.constitutionId] = score.score;
    });
    
    // 生成雷达图指标（按体质ID排序）
    const sortedConstitutionIds = Object.keys(constitutionNames)
      .sort((a, b) => a - b)
      .map(Number);
    
    // 构建指标
    sortedConstitutionIds.forEach(id => {
      indicators.push({
        name: constitutionNames[id],
        max: 100
      });
    });
    
    // 按排序后的体质ID生成数值数组
    const values = sortedConstitutionIds.map(id => 
      parseFloat(scoreMap[id] || 0)
    );
    
    // 获取体质类型
    const result = await getAnswerResultList({ id: currentResultId.value });
    let constitutionType = '未知体质';
    
    if (result.code === 0 && result.data && result.data.length > 0) {
      constitutionType = parseConstitutionType(result.data[0].answerlistResult);
    }
    
    // 设置雷达图选项
    radarChartInstance.setOption({
      backgroundColor: '#f9f6f2',
      tooltip: {
        trigger: 'item',
        formatter: params => {
          const values = params.value;
          let html = `<div style="font-family:KaiTi;padding:5px;">
                      <div style="font-weight:bold;margin-bottom:5px;">${params.name}</div>`;
          
          indicators.forEach((item, index) => {
            html += `<div>${params.marker} ${item.name}: ${values[index]}</div>`;
          });
          
          html += '</div>';
          return html;
        },
        backgroundColor: 'rgba(255, 248, 220, 0.9)',
        borderColor: '#D2B48C'
      },
      legend: {
        data: [constitutionType],
        bottom: 0,
        textStyle: {
          color: '#8B4513',
          fontFamily: 'KaiTi',
          fontSize: 14
        }
      },
      radar: {
        indicator: indicators,
        shape: 'circle',
        splitNumber: 5,
        center: ['50%', '50%'],
        radius: '65%',
        axisName: {
          color: '#8B4513',
          fontFamily: 'KaiTi'
        },
        splitArea: {
          areaStyle: {
            color: ['rgba(255, 248, 220, 0.3)', 'rgba(245, 222, 179, 0.3)']
          }
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(139, 69, 19, 0.3)'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(139, 69, 19, 0.3)'
          }
        }
      },
      series: [{
        type: 'radar',
        name: constitutionType,
        data: [{
          value: values,
          name: constitutionType,
          areaStyle: {
            opacity: 0.2
          },
          lineStyle: {
            width: 2
          },
          itemStyle: {
            color: '#8B4513'
          }
        }]
      }]
    });
    
  } catch (error) {
    console.error('渲染雷达图失败:', error);
    ElMessage.error('图表数据加载失败');
  } finally {
    radarChartInstance.hideLoading();
  }
};

// 添加窗口大小变化监听
window.addEventListener('resize', () => {
  if (radarChartInstance) {
    radarChartInstance.resize();
  }
  if (trendChartInstance) {
    trendChartInstance.resize();
  }
});

// 在组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', () => {
    if (radarChartInstance) {
      radarChartInstance.resize();
    }
    if (trendChartInstance) {
      trendChartInstance.resize();
    }
  });
  
  if (radarChartInstance) {
    radarChartInstance.dispose();
    radarChartInstance = null;
  }
  
  if (trendChartInstance) {
    trendChartInstance.dispose();
    trendChartInstance = null;
  }
});


// 完成回访操作（示例）
const completeFollowup = (id) => {
  ElMessage.success('回访已完成');
  // 这里应该调用更新状态的API
  // 然后重新加载数据
  loadBshfData();
};

// 加载所有问卷信息
const loadQuestionnaires = async () => {
  try {
    const res = await getAllQuestionnaires();
    if (res?.code === 0 && Array.isArray(res.data)) {
      questionnaireMap.value = {};
      res.data.forEach(q => {
        questionnaireMap.value[q.id] = q.queslistName;
      });
    }
  } catch (error) {
    console.error('加载问卷信息失败:', error);
  }
};

// 加载辨识回访数据
const loadBshfData = async () => {
  if (!doctorId.value) return;
  
  loading.value = true;
  try {
    // 先加载所有问卷信息
    await loadQuestionnaires();
    
    // 获取辨识回访列表
    const res = await getBSHFList({
      doctorId: doctorId.value,
      del: 0
    });
    
    if (res.code === 0) {
      bshfList.value = res.data || [];
      
      // 收集所有需要查询的用户ID和结果ID
      const userIds = [...new Set(bshfList.value.map(item => item.userinfoId))];
      const resultIds = [...new Set(bshfList.value.map(item => item.resultId))];
      
      // 并行查询用户信息和结果信息
      await Promise.all([
        loadUserInfo(userIds),
        loadResultInfo(resultIds)
      ]);
    } else {
      ElMessage.error(res.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('加载辨识回访数据失败:', error);
    ElMessage.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 加载用户信息
const loadUserInfo = async (userIds) => {
  if (!userIds.length) return;
  
  try {
    // 查询所有用户信息
    const promises = userIds.map(id => 
      getUserList({ id: id, del: 0 })
    );
    
    const results = await Promise.all(promises);
    
    // 构建用户映射
    results.forEach(res => {
      if (res.code === 0 && res.data && res.data.length > 0) {
        const user = res.data[0];
        userMap.value[user.id] = user.name;
      }
    });
  } catch (error) {
    console.error('加载用户信息失败:', error);
  }
};

// 加载结果信息
const loadResultInfo = async (resultIds) => {
  if (!resultIds.length) return;
  
  try {
    // 查询所有结果信息
    const promises = resultIds.map(id => 
      getAnswerResultList({ id: id })
    );
    
    const results = await Promise.all(promises);
    
    // 构建结果映射
    results.forEach(res => {
      if (res.code === 0 && res.data && res.data.length > 0) {
        const result = res.data[0];
        resultMap.value[result.id] = parseConstitutionType(result.answerlistResult);
      }
    });
  } catch (error) {
    console.error('加载结果信息失败:', error);
  }
};

// 添加跳转到聊天室的方法
const goToChat = () => {
  // 检查是否有医生登录信息
  const doctorInfo = localStorage.getItem('doctorInfo');
  if (!doctorInfo) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }
  
  try {
    const doctor = JSON.parse(doctorInfo);
    const doctorId = doctor.id;
    
    if (!doctorId) {
      ElMessage.error('无法获取医生ID，请重新登录');
      router.push('/login');
      return;
    }
    
    // 跳转到聊天页面，传递医生ID和模式
    router.push({
      path: '/chat',
      query: {
        doctorId: doctorId,
        mode: 'doctor' // 标识当前是医生模式
      }
    });
  } catch (error) {
    console.error('解析医生信息失败:', error);
    ElMessage.error('获取医生信息失败，请重新登录');
    router.push('/login');
  }
};

// 添加退出登录方法
const handleLogout = () => {
  localStorage.removeItem('doctorInfo');
  router.push('/');
};

onMounted(() => {
  // 检查是否有医生登录信息
  const doctorInfo = localStorage.getItem('doctorInfo');
  if (!doctorInfo) {
    router.push('/login');
    return;
  }
  
  try {
    const doctor = JSON.parse(doctorInfo);
    doctorName.value = doctor.name || '医生';
    doctorId.value = doctor.id;
    
    // 加载辨识回访数据
    loadBshfData();
  } catch (e) {
    console.error('解析医生信息失败', e);
  }
});
</script>

<style scoped src="../css/doctor.css"></style>
